package com.dbh.alg.algorithm.hot100.链表;

import com.dbh.alg.algorithm.hot100.ListNode;

public class Leetcode142_环形链表2 {

    public ListNode detectCycle(ListNode head) {
        ListNode p1 = head;
        ListNode p2 = head;
        while (p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
            if (p1 == p2) {
                p1 = head;
                while (true) {
                    if (p1 == p2) {
                        return p1;
                    }
                    p1 = p1.next;
                    p2 = p2.next;
                }
            }
        }
        return null;
    }
}
